# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon, xguo

from tornado import gen
import requests

from coin.base.timestamp import get_timestamp
from coin.exchange.base.rest.private_queryer_context_base import PrivateQueryContextBase


class FuturesPrivateQueryContextBase(PrivateQueryContextBase):
  @gen.coroutine
  def _query_position(self):
    if self._stopped:
      return

    # noinspection PyBroadException
    try:
      update = yield self._async_private_client.async_query_account_position()
      timestamp = get_timestamp()
      if update is not None:
        self._on_response('query_position', timestamp, update.msg)
    except requests.exceptions.Timeout as e:
      self._logger.error('query_account_position timeout! %s' % e)
    except Exception as e:
      self._logger.exception('query_account_balance exception: %s' % e)

  @gen.coroutine
  def _run_query(self):
    self._querying = True
    self._logger.debug('Start querying %d products' % len(self._products))
    try:
      self._query_position()
      self._query_balance()
      for product in self._products:
        self._query_list_orders(product)
    finally:
      self._querying = False
      if not self._stopped:
        self._logger.debug('Query done')
      else:
        self._logger.debug('Stopped')
